package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-08-23
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    //@Cacheable(value = "dict",keyGenerator = "keyGenerator")

    @Override
    @Cacheable(value = "dict", key = "'selectIndexList'+#pid")
    public List<Dict> getChildListByParentId(Long pid) {
        // 根据父id查询数据字典数据
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", pid);
        List<Dict> dicts = baseMapper.selectList(queryWrapper);
        // 遍历子级，获取到之后，需要判断是否有子级
        for (Dict dict : dicts) {
            dict.setHasChildren(isHasChild(dict.getId()));
        }
        return dicts;
    }

    @Override
    public void downloadExcel(HttpServletResponse response) throws IOException {
        // 调用mapper获取所有的字典信息
        List<Dict> dictList = baseMapper.selectList(null);
        // 创建一个DictEeVo的列表，用于数据字典导出excel需要写入的数据
        List<DictEeVo> dictEeVoList = new ArrayList<>(dictList.size());
        // 遍历给DictEeVo赋值
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            // 调用工具类给其进行赋值
            BeanUtils.copyProperties(dict, dictEeVo); // 要求两个对象所属的类的属性名需要一致
            // 添加对象到列表中
            dictEeVoList.add(dictEeVo);
        }
        // 下载：设置响应头
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("字典文件", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 此处必须使用响应流数据，不能写本地地址，否则文件下载就会是下载在服务器端而不是我们想要的下载在浏览器端
        EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("字典列表数据").doWrite(dictEeVoList);
    }

    // 上传导入时，清空缓存，allEntries把其dict空间全部清空
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void upload(MultipartFile file) throws IOException {
        // 文件上传
        EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet(0).doRead();
    }

    @Override
    public String getNameByValue(Long value) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("value", value);
        Dict dict = baseMapper.selectOne(queryWrapper);
        if(dict != null) {
            return dict.getName();
        }
        return null;
    }

    @Override
    public String getNameByDictCodeAndValue(String dictCode, Long value) {
        // 先根据编码获取id
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);
        // 再根据parent_id和value值获取对应的文字
        QueryWrapper<Dict> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("parent_id", dict.getId());
        queryWrapper1.eq("value", value);
        Dict dict1 = baseMapper.selectOne(queryWrapper1);
        return dict1.getName();
    }

    private boolean isHasChild(Long pid) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", pid);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
